package crmdna.member;

import static crmdna.common.OfyService.ofy;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import crmdna.common.APIException;
import crmdna.common.APIResponse.Status;

// TODO: move the get methods to MemberLoader
public class UnverifiedProgram {
	public static List<UnverifiedProgramProp> getUnverifiedPrograms(
			String client, long memberId, String login) {

		// this is just a convenience function. it uses the corresponding array
		// function
		MemberLoader.safeGet(client, memberId, login);

		List<Long> memberIds = new ArrayList<>();
		memberIds.add(memberId);

		Map<Long, List<UnverifiedProgramProp>> map = getUnverifiedPrograms(
				client, memberIds);

		if (map.size() == 0)
			return null;

		if (!map.containsKey(memberId)) {
			// should never get here
			throw new APIException(Status.ERROR_INTERNAL,
					"Cannot find memberId [" + memberId
							+ "] in map returned by getUnverifiedPrograms");
		}

		return map.get(memberId);
	}

	public static Map<Long, List<UnverifiedProgramProp>> getUnverifiedPrograms(
			String client, List<Long> memberIds) {

		Map<Long, MemberEntity> membersMap = ofy(client).load()
				.type(MemberEntity.class).ids(memberIds);

		Map<Long, List<UnverifiedProgramProp>> unverifiedProgramsMap = new HashMap<>();

		for (Long memberId : membersMap.keySet()) {
			MemberEntity memberEntity = membersMap.get(memberId);
			String json = memberEntity.listUnverfiedProgramPropJson;

			Gson gson = new Gson();
			Type type = new TypeToken<List<UnverifiedProgramProp>>() {
			}.getType();

			List<UnverifiedProgramProp> list = gson.fromJson(json, type);
			unverifiedProgramsMap.put(memberId, list);
		}

		return unverifiedProgramsMap;
	}
	
	static List<UnverifiedProgramProp> getUnverifiedProgramPropsFromJson(
			String json) {
		Gson gson = new Gson();
		Type type = new TypeToken<List<UnverifiedProgramProp>>() {
		}.getType();

		List<UnverifiedProgramProp> list = gson.fromJson(json, type);

		return list;
	}
}
